package com.yang.mybatis.proxy;

import com.yang.mybatis.config.MybatisConfiguration;
import com.yang.mybatis.config.MybatisSqlStatement;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapperProxyFactory {
    private Map<Class, MapperProxy> mapperProxyMap = new HashMap<>();


    public MapperProxyFactory(MybatisConfiguration mybatisConfiguration) {
        Map<String, List<MybatisSqlStatement>> mapperName2SqlStatementsMap = mybatisConfiguration.getMapper2SqlStatementsMap();
        mapperName2SqlStatementsMap.forEach((mapperName, sqlStatementList) -> {
            try {
                Class<?> type = Class.forName(mapperName);
                mapperProxyMap.put(type, new MapperProxy(type, sqlStatementList));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public Object newInstance(Class mapperType) {
        MapperProxy mapperProxy = mapperProxyMap.get(mapperType);
        return Proxy.newProxyInstance(mapperType.getClassLoader(),
                new Class[]{mapperType},
                mapperProxy);
    }

}
